package com.example.mybatisplus.controller;

import com.example.mybatisplus.common.JsonResponse;
import com.example.mybatisplus.model.domain.User;
import com.example.mybatisplus.service.LoginService;
import com.example.mybatisplus.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import static com.example.mybatisplus.common.Constants.*;

@RestController
@RequestMapping("/api/login")
public class LoginController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private UserService userService;

    @PostMapping("")
    private JsonResponse login(@RequestBody User user){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getStuUsername(),user.getStuPassword());
        try{
            subject.login(token);
            User user1 = loginService.login(user);
            return JsonResponse.success(user1).setMessage("登陆成功");
        }catch (UnknownAccountException e){
            return JsonResponse.failure(e.getMessage());
        }catch (IncorrectCredentialsException e){
            return JsonResponse.failure("密码错误");
        }
    }

    @GetMapping("/user/logout")
    public JsonResponse logout() {

        Subject subject = SecurityUtils.getSubject();

        subject.logout();

        return JsonResponse.success().setMessage("登出成功");
    }
}
